/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ee.ut.math.esi.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author ool
 */
public class LocationFinder {

    private AlchemyApiResource resource;
    private static int MAX_SCRIPT_SIZE = 150000;

    public LocationFinder() {
        resource = new AlchemyApiResource();
    }

    public Set<String> getLocationsFromURL(URL url) throws ParserConfigurationException, SAXException, IOException {
        Set<String> result = new TreeSet<String>();
        String script = getScript(url);
        List<String> test = getScriptParts(script);
        for (String scriptPart : test) {
            Node node = resource.searchEntities(scriptPart);
            result.addAll(AlchemyApiResponseService.getLocationsFromAlchemyAPIResult(node));
        }
        return result;
    }

    private String getScript(URL url) throws ParserConfigurationException, SAXException, IOException {
        StringBuilder buffer = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        boolean sourceTextHasStarted = false;
        while ((inputLine = in.readLine()) != null) {
            if (sourceTextHasStarted) {
                inputLine = inputLine.replaceAll("\\b\\s{2,}\\b", " ");
                inputLine = inputLine.replace("<b>", "");
                inputLine = inputLine.replace("</b>", "");
                if (inputLine.contains("</pre>")) {
                    buffer.append(inputLine.substring(0, inputLine.indexOf("</pre>")));
                    break;
                }
                buffer.append(inputLine);
                buffer.append(System.getProperty("line.separator"));
            }
            if (inputLine.contains("<td class=scrtext>")) {
                inputLine = inputLine.replace("<html><head></head><body>", "");
                inputLine = inputLine.replaceAll("\\b\\s{2,}\\b", " ");
                inputLine = inputLine.replace("<b>", "");
                inputLine = inputLine.replace("</b>", "");
                buffer.append(inputLine.substring(inputLine.indexOf("<pre>") + 5));
                sourceTextHasStarted = true;
            }
        }
        in.close();
        return buffer.toString();
    }

    private List<String> getScriptParts(String script) {
        List<String> result = new ArrayList<String>();
        String part1 = "";
        String part2 = "";
        if (script.length() > MAX_SCRIPT_SIZE) {
            int charPos = MAX_SCRIPT_SIZE;
            int splitPos = 0;
            for (; true; splitPos++) {
                if (script.charAt(charPos - splitPos) == '\n') {
                    break;
                }
            }
            part1 = script.substring(0, charPos - splitPos);
            part2 = script.substring(charPos - splitPos);
            for (String f : getScriptParts(part1)) {
                result.add(f);
            }
            for (String s : getScriptParts(part2)) {
                result.add(s);
            }
        } else {
            result.add(script);
        }
        return result;
    }
}
